package com.ai.web.app;

import java.util.Map;

import org.apache.log4j.Logger;

import com.baidu.yun.channel.auth.ChannelKeyPair;
import com.baidu.yun.channel.client.BaiduChannelClient;
import com.baidu.yun.channel.exception.ChannelClientException;
import com.baidu.yun.channel.exception.ChannelServerException;
import com.baidu.yun.channel.model.PushUnicastMessageRequest;
import com.baidu.yun.channel.model.PushUnicastMessageResponse;
import com.baidu.yun.core.log.YunLogEvent;
import com.baidu.yun.core.log.YunLogHandler;

public class AndroidPushNotification {

	private static Logger logger = Logger.getLogger(QueryBindList.class);
	
    public static boolean pushMsg(long channelId, String userId, String msgTitle, String msgDesc, Map<String, String> msgCustomMap) {
    	boolean result = false;
        /*
         * @brief 推送单播通知(Android Push SDK拦截并解析) message_type = 1 (默认为0)
         */

        // 1. 设置developer平台的ApiKey/SecretKey
        ChannelKeyPair pair = new ChannelKeyPair(AppContext.apiKey, AppContext.secretKey);

        // 2. 创建BaiduChannelClient对象实例
        BaiduChannelClient channelClient = new BaiduChannelClient(pair);

        // 3. 若要了解交互细节，请注册YunLogHandler类
        channelClient.setChannelLogHandler(new YunLogHandler() {
            public void onHandle(YunLogEvent event) {
                logger.info(event.getMessage());
            }
        });

        try {

            // 4. 创建请求类对象
            // 手机端的ChannelId， 手机端的UserId， 先用1111111111111代替，用户需替换为自己的
            PushUnicastMessageRequest request = new PushUnicastMessageRequest();
            request.setDeviceType(3); // device_type => 1: web 2: pc 3:android
                                      // 4:ios 5:wp
            request.setMessageType(0);
            
            request.setChannelId(channelId);
            request.setUserId(userId);
            
            StringBuilder sb = new StringBuilder();
            sb.append("{\"title\":\"");
            sb.append(msgTitle);
            sb.append("\",\"description\":\"");
            sb.append(msgDesc);
            sb.append("\"");
            if (msgCustomMap != null && !msgCustomMap.isEmpty()) {
	            StringBuilder params = new StringBuilder();
	            params.append(", \"custom_content\": {");
	            for (String key : msgCustomMap.keySet()) {
	            	params.append("\"");
	            	params.append(key);
	            	params.append("\":\"");
	            	params.append(msgCustomMap.get(key));
	            	params.append("\",");
	            }
	            sb.append(params.substring(0, params.length() - 1));
	            sb.append("}");
            }
            sb.append("}");
            logger.info("push msg:" + sb.toString());
            
            request.setMessage(sb.toString());
            
            // 5. 调用pushMessage接口
            PushUnicastMessageResponse response = channelClient
                    .pushUnicastMessage(request);
            response.getSuccessAmount();
            // 6. 认证推送成功
            logger.info("push amount : " + response.getSuccessAmount());
            result = true;

        } catch (ChannelClientException e) {
            // 处理客户端错误异常
            logger.error(e.getMessage(), e);
        } catch (ChannelServerException e) {
            // 处理服务端错误异常
            logger.error(String.format(
                    "request_id: %d, error_code: %d, error_message: %s",
                    e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
        }
        return result;
    }

}
